# -*- coding: utf-8 -*-

# 百度获取日历
# https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=2020%E5%B9%B4&resource_id=6018&format=json


import requests
import json
import sys

# 获取法定节假日
def get_holiday(year=2021,month=12):
    result = set([])
    url = 'https://sp1.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?tn=wisetpl&format=json&resource_id=39043&query=%d年%d月&cb=jsonp_1626770999317_26492' % (year, month)
    html = requests.get(url)
    if html.status_code == 200:
        reponse = html.text
        index = reponse.find('{')
        rindex = reponse.rfind('}')
        reponse = reponse[index : rindex-len(reponse)+1]
        jsondata = json.loads(reponse)
        if 'data' in jsondata and len(jsondata['data']) > 0 and 'almanac' in jsondata['data'][0]:
            almanacs = jsondata['data'][0]['almanac']
            for almanac in almanacs:
                if 'status' in almanac and almanac['status'] == '1':
                    result.add('%04s%02d%02d' % (almanac['year'],int(almanac['month']),int(almanac['day'])))
    return result


def save(year, listdata):
    with open(str(year)+'.UnTradeDate','a') as file:
        for data in listdata:
            file.write(data+'\n')


if __name__=="__main__":
    year = int(sys.argv[1])
    holidays = set([])
    for month in range(1,12):
        holiday = get_holiday(year, month)
        holidays = holidays | holiday
    list_holidays = list(holidays)
    list_holidays.sort()
    save(year,list_holidays)

